# -*- coding: UTF-8 -*-
import os
import random
import time
from datetime import timedelta

import pymysql
from apscheduler.jobstores.redis import RedisJobStore

basedir = os.path.abspath(os.path.dirname(__file__))


class Config(dict):
    # 数据库信息
    DB_HOST = "127.0.0.1"
    DB_PORT = 3306
    DB_USER = "wangps"
    DB_PASSWORD = "wps123456"
    DB_NAME = None

    SECRET_KEY = "xeewxe4xc0xeexb1]x9bxa0x9e)x15Qhemxe5xf17xd6xceBxb7xb4"

    # 总路由
    URL_PATH = "server.urls"
    # 注册蓝图
    INSTALLED_APPS = [
        "server.apps.fund",
        "server.apps.user",
        "server.apps.account",
        "server.apps.share"
    ]

    # JWT设置
    # If true this will only allow the cookies that contain your JWTs to be sent
    # over https. In production, this should always be set to True
    JWT_COOKIE_SECURE = False
    JWT_TOKEN_LOCATION = ["cookies"]
    JWT_SECRET_KEY = SECRET_KEY
    JWT_ACCESS_TOKEN_EXPIRES = timedelta(minutes=40)  # 令牌有效时间 单位秒
    JWT_COOKIE_CSRF_PROTECT = False

    # 数据库连接编码
    DB_CHARSET = "utf8"
    # mincached : 启动时开启的闲置连接数量(缺省值 0 开始时不创建连接)
    DB_MIN_CACHED = 2
    # maxcached : 连接池中允许的闲置的最多连接数量(缺省值 0 代表不闲置连接池大小)
    DB_MAX_CACHED = 5
    # maxshared : 共享连接数允许的最大数量(缺省值 0 代表所有连接都是专用的)如果达到了最大数量,被请求为共享的连接将会被共享使用
    # 此值无效， 因为threadsafty = 1
    DB_MAX_SHARED = 20
    # maxconnecyions : 创建连接池的最大数量(缺省值 0 代表不限制)
    DB_MAX_CONNECYIONS = 100
    # blocking : 设置在连接池达到最大数量时的行为(缺省值 0 或 False 代表返回一个错误<toMany......> 其他代表阻塞直到连接数减少,连接被分配)
    DB_BLOCKING = True
    # maxusage : 单个连接的最大允许复用次数(缺省值 0 或 False 代表不限制的复用).当达到最大数时,连接会自动重新连接(关闭和重新打开)
    DB_MAX_USAGE = 0
    # setsession : 一个可选的SQL命令列表用于准备每个会话，如["set datestyle to german", ...]
    DB_SET_SESSION = None
    # creator : 使用连接数据库的模块
    DB_CREATOR = pymysql

    DB_UNICODE = True

    JSON_AS_ASCII = False
    JSONIFY_MIMETYPE = "application/json;charset=utf-8"

    # Redis 配置  RDB
    RDB_HOST = "127.0.0.1"
    RDB_PORT = 6379
    RDB_PWD = None
    RDB_DB = 0
    LOCK_WAIT = 5  # 加锁等待时间
    LOCK_INTERVAL = 0.5  # 加锁判断间隔时间

    # 日志配置
    LOG_LEVEL = "DEBUG"
    LOG_FILENAME = "fund.log"
    LOG_MAX_BYTES = 50 * 1024 * 1024  # 50M
    LOG_BACKUP_COUNT = 5  # 日志备份个数

    # 定时任务配置
    JOBS = [
        {
            "id": "background",
            # "func": Spider.get_fund_worth,
            "func": "server.apps.fund.spider:Spider.get_fund_worth",
            "args": None,
            "trigger": {
                "type": "cron",
                "day_of_week": "0-4",
                "hour": "19-23",
                "minute": "*/3"  # 每3分钟跑一次
            }
        }
    ]
    # # 存储位置
    # SCHEDULER_JOBSTORES = {
    #     'default': RedisJobStore(host=RDB_HOST, port=RDB_PORT, password=RDB_PWD)
    # }
    # 线程池配置
    SCHEDULER_EXECUTORS = {
        'default': {'type': 'threadpool', 'max_workers': 20}
    }
    # 配置时区
    SCHEDULER_TIMEZONE = 'Asia/Shanghai'
    SCHEDULER_JOB_DEFAULTS = {
        'coalesce': False,
        'max_instances': 3
    }
    # 调度器开关
    SCHEDULER_API_ENABLED = True

    DEBUG = True

    # 数据库配置
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    # 连接池 add
    SQLALCHEMY_RECORD_QUERIES = True
    SQLALCHEMY_POOL_SIZE = 1024
    # SQLALCHEMY_POOL_TIMEOUT = 90
    # SQLALCHEMY_POOL_RECYCLE = 3
    SQLALCHEMY_POOL_TIMEOUT = 10800  # 3个小时
    # SQLALCHEMY_POOL_RECYCLE = -1
    SQLALCHEMY_POOL_RECYCLE = 10800  # 3个小时回收
    SQLALCHEMY_MAX_OVERFLOW = 1024


class DevelopmentConfig(Config):
    # 运行参数
    DEBUG = False
    ENV = "development"
    # 数据库信息
    DB_HOST = "127.0.0.1"
    DB_NAME = "finance_dev"
    DB_USER = "root"
    DB_PORT = 3306
    DB_PASSWORD = "wps123456"
    DB_URI = 'mysql+pymysql://{db_username}:{db_password}@{db_host}:{db_port}/{db_name}' \
        .format(db_username=DB_USER, db_password=DB_PASSWORD, db_host=DB_HOST, db_port=DB_PORT, db_name=DB_NAME)
    SQLALCHEMY_DATABASE_URI = DB_URI
    # redis库名
    RDB_DB = 1


class TestingConfig(Config):
    # 数据库信息
    DB_NAME = "finance_dev"
    # redis库名
    RDB_DB = 1


class ProductionConfig(Config):
    ENV = "production"
    DEBUG = False

    # 数据库信息
    DB_HOST = "127.0.0.1"
    DB_NAME = "finance"
    DB_USER = "root"
    DB_PORT = 3306
    DB_PASSWORD = "wps123456"
    DB_URI = 'mysql+pymysql://{db_username}:{db_password}@{db_host}:{db_port}/{db_name}' \
        .format(db_username=DB_USER, db_password=DB_PASSWORD, db_host=DB_HOST, db_port=DB_PORT, db_name=DB_NAME)
    SQLALCHEMY_DATABASE_URI = DB_URI
    # redis库名
    RDB_DB = 0


config = {
    'dev': DevelopmentConfig,
    'test': TestingConfig,
    'prod': ProductionConfig,
    'default': DevelopmentConfig
}
